﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common.Model;
using BLL;
namespace stock.GuPiao
{
    public partial class Weather : System.Web.UI.Page
    {
        BLL.WeatherAlertBLL weatherBL = new WeatherAlertBLL();
        int ssl = 0;
        public bool ordered
        {
            get
            {
                if (ViewState["Ordered"] == null)
                {
                    ViewState["Ordered"] = false;
                }
                return (bool)ViewState["Ordered"];
            }
            set { ViewState["Ordered"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                IniData();
            }
        }

        private void IniData()
        {
            if (Session["id"] == null)
            {
                Response.Redirect("login.aspx");
            }
            else
            {
                hfId.Value = Session["id"].ToString();
            }
            List<WeatherAlert> alertModels = weatherBL.GetModelList(" CustomerId=" + Session["id"].ToString());
            lbWeather.Text = "";
            if (alertModels != null && alertModels.Count > 0)
            {
                foreach (WeatherAlert model in alertModels)
                {
                    Citys cityModel = (new CitysBLL()).GetModel(model.CityId);
                    if (cityModel != null)
                    {
                        lbWeather.Text += "地区：" + cityModel.Name;
                    }
                }
                btCancel.Enabled = true;
                btCancel.Visible = true;
                ordered = true;
                btAdd.Text = "修 改";
                btTest.Enabled = true;
                btTest.Visible = true;
            }
            else
            {
                btCancel.Visible = false;
                btCancel.Enabled = false;
                btTest.Visible = false;
                btTest.Enabled = false;
            }
            ProvincesBLL proBLL = new ProvincesBLL();
            CitysBLL cityBLL = new CitysBLL();
            ddlProvince.DataSource = proBLL.GetAllList().Tables[0];
            ddlProvince.DataValueField = "Number";
            ddlProvince.DataTextField = "Name";
            ddlProvince.SelectedIndex = ssl;
            ddlProvince.DataBind();
            ddlCity.DataSource = cityBLL.GetList(" fatherNumber= '" + ddlProvince.SelectedValue + "' ").Tables[0];
            ddlCity.DataValueField = "Id";
            ddlCity.DataTextField = "Name";
            ddlCity.DataBind();
        }

        protected void btAdd_Click(object sender, EventArgs e)
        {
            if (Session["id"] == null)
            {
                Response.Redirect("login.aspx");
                return;
            }
            String Uid = hfId.Value;
            if (ordered == true)
            {
                List<WeatherAlert> alertModels = weatherBL.GetModelList(" CustomerId=" + Uid);
                if (alertModels != null && alertModels.Count > 0)
                {
                    foreach (WeatherAlert alertModel in alertModels)
                    {
                        alertModel.CityId = int.Parse(ddlCity.SelectedValue);
                        weatherBL.Update(alertModel);
                    }
                }
            }
            else
            {
                WeatherAlert alertModle = new WeatherAlert();
                alertModle.CityId = int.Parse(ddlCity.SelectedValue);
                alertModle.CustomerId = int.Parse(hfId.Value);
                alertModle.CreateTime = DateTime.Now;
                weatherBL.Add(alertModle);
                ordered = true;
            }
            IniData();
        }

        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            ssl = ddlProvince.SelectedIndex;
            IniData();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            String Uid = hfId.Value;
            List<WeatherAlert> alertModels = weatherBL.GetModelList(" CustomerId=" + Uid);
            if (alertModels != null && alertModels.Count > 0)
            {
                foreach (WeatherAlert alertModel in alertModels)
                {
                    weatherBL.Delete(alertModel.Id);
                }
                ordered = false;
            }
            IniData();
        }

        protected void btTest_Click(object sender, EventArgs e)
        {
            if (ordered == true)
            {
                Customer userModel = (new CustomerBLL()).GetModel(int.Parse(hfId.Value));
                List<WeatherAlert> alertModels = weatherBL.GetModelList(" CustomerId=" + hfId.Value);
                if (alertModels != null && alertModels.Count > 0)
                {
                    foreach (WeatherAlert alertModel in alertModels)
                    {
                        Citys cityModel = (new CitysBLL()).GetModel(alertModel.CityId);
                        WeatherVirtual temp = GetWeatherByCity(cityModel.Number);
                        String body;
                        if (temp.weatherinfo.fchh == "08")
                        {
                            body = temp.weatherinfo.date_y + "," + temp.weatherinfo.week + "-今天:"
                           + temp.weatherinfo.weather1 + "," + temp.weatherinfo.temp1 + "," + temp.weatherinfo.wind1
                           + ";明天:" + temp.weatherinfo.weather2 + "," + temp.weatherinfo.temp2 + "," + temp.weatherinfo.wind2
                           + ";后天:" + temp.weatherinfo.weather3 + "," + temp.weatherinfo.temp3 + "," + temp.weatherinfo.wind3
                           + ";大后天:" + temp.weatherinfo.weather4 + "," + temp.weatherinfo.temp4 + "," + temp.weatherinfo.wind4 + ";48小时穿衣指数:" + temp.weatherinfo.index48_d;
                        }
                        else
                        {
                            body = temp.weatherinfo.date_y + "," + temp.weatherinfo.week + "-今天:"
                          + temp.weatherinfo.weather1 + ","+ temp.weatherinfo.wind1
                          + ";明天:" + temp.weatherinfo.weather2 + ","  + temp.weatherinfo.wind2
                          + ";后天:" + temp.weatherinfo.weather3 + ","  + "," + temp.weatherinfo.wind3
                          + ";大后天:" + temp.weatherinfo.weather4 + "," + "," + temp.weatherinfo.wind4 + ";48小时穿衣指数:" + temp.weatherinfo.index48_d;
                        }
                      Boolean back= BLL.Tools.SendMail(userModel.Email, body, temp.weatherinfo.city + ":" + temp.weatherinfo.weather1, null, false);
                      if (back)
                      {
                          btTest.Enabled = false;
                          string script = "<script language='Javascript'>alert('已经发送到您的邮箱了，请注意查看！');</script>";
                          Page.ClientScript.RegisterStartupScript(this.GetType(), "", script);
                          return;
                      }
                      else
                      {
                          btTest.Enabled = false;
                          string script = "<script language='Javascript'>alert('未知错误！');</script>";
                          Page.ClientScript.RegisterStartupScript(this.GetType(), "", script);
                      }
                    }
                }
            }
        }
        public WeatherVirtual GetWeatherByCity(String Number)
        {
            String strUrl = "http://m.weather.com.cn/data/" + Number + ".html";
            Uri uri = new Uri(strUrl);
            string data;
            System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.Stream str3 = resp.GetResponseStream();
            System.IO.StreamReader readers = new System.IO.StreamReader(str3, System.Text.Encoding.UTF8);
            data = readers.ReadToEnd();
            readers.Close();
            resp.Close();
            System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
            WeatherVirtual weatherTemp = json.Deserialize<WeatherVirtual>(data);
            return weatherTemp;
        }
    }
}